package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.enums.DeliveryAreaEnum;
import com.yuanda.erp9.syn.enums.SourceEnum;
import com.yuanda.erp9.syn.enums.SubjectSupplierEnum;
import com.yuanda.erp9.syn.exception.TargetServerException;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.helper.Chip1AdimaxHelper;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.poi.Chip1AdimaxExcelData;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.service.erp9.Chip1AdimaxService;
import com.yuanda.erp9.syn.service.erp9.CmsTopicUpdateSumLogService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

/**
 * @ClassName Chip1AdimaxServiceImpl
 * @Description
 * @Date 2023/2/8
 * @Author myq
 */
@Slf4j
@Service
public class Chip1AdimaxServiceImpl implements Chip1AdimaxService {

    @Autowired
    private RetryOperateLogHelper retryOperateLogHelper;

    @Autowired
    private Chip1AdimaxHelper chip1AdimaxHelper;

    @Autowired
    private CmsTopicUpdateSumLogService cmsTopicUpdateSumLogService;

    private final String SUPPLIER = "Kyber Electronics Company Ltd.";
    private final String US_CODE = "US000006801";

    /**
     * @param excelPath
     * @param pk
     * @Description: 解析chip1Adimax数据
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/2/89:46
     */
    @Override
    public void parse(String excelPath, Long pk) {
        AtomicInteger index = new AtomicInteger(0);
        AtomicInteger sum = new AtomicInteger(0);
        Set<String> mfrPartSet = new HashSet<>();
        CacheUtil.Cache brandCache = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
        CacheUtil.Cache supplierCache = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey());
        Integer supplierId = supplierCache.get(SUPPLIER);
        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, "chip1-adimax", SourceEnum.EMAIL.getCode());
        try {
            EasyExcelUtils.readExcel(excelPath, Chip1AdimaxExcelData.class, new Consumer<Chip1AdimaxExcelData>() {
                @Override
                public void accept(Chip1AdimaxExcelData chip1AdimaxExcelData) {
                    try {
                        sum.incrementAndGet();
                        CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
                        CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();
                        cmsGoodsEntity.setAdminid(0);
                        cmsGoodsEntity.setTenantsid(0);
                        cmsGoodsEntity.setClassifyid(0);
                        cmsGoodsEntity.setImg("");
                        cmsGoodsEntity.setType(0);
                        cmsGoodsEntity.setStatus(1);
                        cmsGoodsEntity.setStatusMsg("");
                        cmsGoodsEntity.setDataType(1);
                        cmsGoodsEntity.setModel(chip1AdimaxExcelData.getMfrPart());
                        CmsBrandsTempEntity cmsBrandsTempEntity = new CmsBrandsTempEntity();
                        cmsBrandsTempEntity.setTag(0);
                        String brand = chip1AdimaxExcelData.getMfr();
                        cmsBrandsTempEntity.setName(StringUtils.isNotEmpty(brand) ? brand : "unknown_brand");
                        Integer brandId = brandCache.insertAndGet(cmsBrandsTempEntity);
                        cmsGoodsEntity.setBrand(brandId);
                        cmsGoodsEntity.setBrandName(brand);
                        cmsGoodsEntity.setSupplier(supplierId);
                        cmsGoodsEntity.setSplName(SUPPLIER);
                        String mfrPart = chip1AdimaxExcelData.getMfrPart();
                        String sign;
                        if (mfrPartSet.contains(mfrPart)) {
                            sign = "chip1-adimax_" + mfrPart + ("_" + index.incrementAndGet());
                        } else {
                            mfrPartSet.add(mfrPart);
                            sign = "chip1-adimax_" + mfrPart;
                        }
                        String incodes = EasyExcelUtils.getIncodes(sign, US_CODE, supplierId);
                        cmsGoodsEntity.setIncodes(incodes);
                        cmsGoodsEntity.setGoodid(incodes);
                        cmsGoodsEntity.setIsSampleApply(0);
                        cmsGoodsEntity.setBatch("");
                        cmsGoodsEntity.setOriginalPrice(new BigDecimal("0.00"));
                        cmsGoodsEntity.setPurchasePrice(new BigDecimal("0.00"));
                        cmsGoodsEntity.setRepertory(StringUtils.isNotEmpty(chip1AdimaxExcelData.getAvailQty()) ? Integer.parseInt(chip1AdimaxExcelData.getAvailQty()) : 0);
                        cmsGoodsEntity.setRepertoryArea("海外");
                        cmsGoodsEntity.setPublish(1);
                        cmsGoodsEntity.setDescribe("");
                        cmsGoodsEntity.setFiles("");
                        cmsGoodsEntity.setPayType(0);
                        Long restriction = Long.parseLong(chip1AdimaxExcelData.getMoq());
                        long max = Math.max(restriction.intValue(), 1L);
                        cmsGoodsEntity.setMinimumOrder(max);
                        cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.DOMESTIC.getCode());
                        cmsGoodsEntity.setDomesticDate("15-20工作日");
                        cmsGoodsEntity.setHongkongDate("");
                        cmsGoodsEntity.setIncremental(max);
                        cmsGoodsEntity.setSource(SourceEnum.EMAIL.getCode());
                        cmsGoodsEntity.setMpq(max);
                        cmsGoodsEntity.setHisp("chip1-adimax");

                        cmsGoodsEntity.setSales(0);
                        cmsGoodsEntity.setClick(0);
                        cmsGoodsEntity.setVisitor(0);
                        cmsGoodsEntity.setCreatedAt(DateUtils.now());
                        cmsGoodsEntity.setUpdatedAt(DateUtils.now());
                        cmsGoodsEntity.setActivityId(0);
                        cmsGoodsEntity.setContent(null);

                        //费率
                        JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());
                        // 费率信息
                        JSONObject rateJsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);
                        cmsGoodsEntity.setRates(rateJsonObject);
                        //关税
                        BigDecimal tariffRate = rateJsonObject.getBigDecimal(RateCalculateConstants.TARIFFRATE_FIELD);
                        //商检税
                        BigDecimal cIQprice = rateJsonObject.getBigDecimal(RateCalculateConstants.CIQPRICE_FIELD);
                        //税费计算和存储
                        if (tariffRate != null) {
                            cmsGoodsEntity.setTariffsRate(tariffRate.doubleValue());
                        }
                        if (cIQprice != null) {
                            cmsGoodsEntity.setInspectionChargesFee(cIQprice.doubleValue());
                        }
                        cmsGoodsEntity.setEmbargo(data.get(RateCalculateConstants.EMBARGO_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.EMBARGO_FIELD));
                        cmsGoodsEntity.setCcc(data.get(RateCalculateConstants.CCC_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.CCC_FIELD));
                        cmsGoodsEntity.setEccnNo(data.getString(RateCalculateConstants.ECCN_FIELD));
                        // 参数
                        cmsGoodsEntity.setParams(null);

                        // 阶梯价格
                        List<Map<String, String>> ladderPrice = chip1AdimaxHelper.getLadderPrice(Arrays.asList(chip1AdimaxExcelData.getBreak1(), chip1AdimaxExcelData.getBreak2(), chip1AdimaxExcelData.getBreak3(),
                                        chip1AdimaxExcelData.getBreak4(), chip1AdimaxExcelData.getBreak5(), chip1AdimaxExcelData.getBreak6(), chip1AdimaxExcelData.getBreak7()),
                                Arrays.asList(chip1AdimaxExcelData.getPrice1(), chip1AdimaxExcelData.getPrice2(), chip1AdimaxExcelData.getPrice3(), chip1AdimaxExcelData.getPrice4(),
                                        chip1AdimaxExcelData.getPrice5(), chip1AdimaxExcelData.getPrice6(), chip1AdimaxExcelData.getPrice7())
                        );
                        cmsGoodsEntity.setPrices(JSON.toJSONString(ladderPrice));
                        if (!CollectionUtils.isEmpty(ladderPrice)) {
                            cmsGoodsEntity.setMinimumOrder(Math.max(Long.parseLong(ladderPrice.get(0).get("min")), cmsGoodsEntity.getMinimumOrder()));
//                            cmsGoodsEntity.setUnitPrice(Double.parseDouble(MathUtil.divide(ladderPrice.get(0).get("price"), cmsGoodsEntity.getMinimumOrder(), 4)));
                        } else {
                            cmsGoodsEntity.setUnitPrice(0.0000);
                        }
                        cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

                        CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
                        cmsGoodsInformationEntity.setEcnn(1);
                        cmsGoodsInformationEntity.setAtlas("");
                        cmsGoodsInformationEntity.setContent(null);
                        cmsGoodsInformationEntity.setActivity(0);
                        cmsGoodsInformationEntity.setEcnnnumber("");
                        cmsGoodsInformationEntity.setTariffs(0);
                        cmsGoodsInformationEntity.setGoodid(incodes);
                        cmsGoodsInformationEntity.setTariffsrate(0);
                        cmsGoodsInformationEntity.setInspectionCharges(0);
                        cmsGoodsInformationEntity.setInspectionChargesFee(cmsGoodsEntity.getInspectionChargesFee());
                        cmsGoodsInformationEntity.setParams(null);
                        cmsGoodsInformationEntity.setCreatedAt(new Date());
                        cmsGoodsPojo.setCmsGoodsInformationEntity(cmsGoodsInformationEntity);

                        // price
                        List<CmsPricesEntity> pricesEntities = new ArrayList<>(6);
                        for (Map<String, String> m : ladderPrice) {
                            CmsPricesEntity pricesEntity = new CmsPricesEntity();
                            pricesEntity.setLadderid(0);
                            pricesEntity.setGoodid(incodes);
                            pricesEntity.setMin(Long.parseLong(m.get("min")));
                            pricesEntity.setMax(Long.parseLong(m.get("max")));
                            pricesEntity.setPrice(BigDecimal.valueOf(Double.parseDouble(m.get("price"))));
                            pricesEntity.setCurrency(Integer.parseInt(m.get("currency")));
                            pricesEntity.setPosition(Integer.parseInt(m.get("position")));
                            pricesEntity.setDiscountRate(new BigDecimal(m.get("discount_rate")));
                            pricesEntity.setDiscountPrice(new BigDecimal(m.get("discount_price")));
                            pricesEntity.setPublish(0);
                            pricesEntity.setCreatedAt(new Date());
                            pricesEntity.setUpdatedAt(new Date());
                            pricesEntities.add(pricesEntity);
                        }
                        cmsGoodsPojo.setCmsPricesEntityList(pricesEntities);
                        objectMaster.add(cmsGoodsPojo);
                    } catch (TargetServerException e) {
                        log.warn("Chip1Adimax解析错误：无法连接到目标服务器");
                        throw new TargetServerException(e.getMessage(), supplierId, SubjectSupplierEnum.VANLINKON.getSubject());
                    } catch (Exception e1) {
                        log.warn("Chip1Adimax解析错误,丢弃测数据:{}", e1);
                        retryOperateLogHelper.add(chip1AdimaxExcelData, supplierId, e1.toString(), false);
                    }
                }

            });
        } finally {
            // 退出标志
            objectMaster.isCompleted();
            cmsTopicUpdateSumLogService.insertBySum(sum.longValue(), pk);
        }

    }


}